package leetcode.hot100;

import java.util.Arrays;

/**
 * 2. 两数相加
 *
 * @author: yjf
 * @date: 2024/11/28
 */
public class LeetCode2 {

    public static void main(String[] args) {
        addTwoNumbers(243, 564);        // 7, 0, 8
        addTwoNumbers(9999, 9999999);   // 8, 9, 9, 9, 0, 0, 0, 1
    }

    public static void addTwoNumbers(int l1, int l2) {
        int bit1 = countDigits(l1);
        int bit2 = countDigits(l2);
        int copyBit1 = bit1 - 1;
        int copyBit2 = bit2 - 1;
        int carry = 0;
        int[] res = new int[Math.max(bit1, bit2) + 1];
        int minBit = Math.min(bit1, bit2);
        int index = 0;
        for (; index < minBit; index++) {
            int value1 = (int) (l1 / Math.pow(10, copyBit1));
            int value2 = (int) (l2 / Math.pow(10, copyBit2));
            l1 = (int) (l1 % Math.pow(10, copyBit1));
            l2 = (int) (l2 % Math.pow(10, copyBit2));
            copyBit1--;
            copyBit2--;
            res[index] = (value1 + value2 + carry) % 10;
            carry = (value1 + value2 + carry) / 10;
        }
        while (l1 > 0) {
            int value = ((int) (l1 / Math.pow(10, copyBit1)) + carry);
            res[index++] = value % 10;
            l1 = (int) (l1 % Math.pow(10, copyBit1));
            copyBit1--;
            carry = (value + carry) / 10;
        }
        while (l2 > 0) {
            int value = ((int) (l2 / Math.pow(10L, copyBit2)) + carry);
            res[index++] = value % 10;
            l2 = (int) (l2 % Math.pow(10, copyBit2));
            copyBit2--;
            carry = (value + carry) / 10;
        }
        if (carry > 0) {
            res[index++] = carry;
        }
        System.out.println(Arrays.toString(res));
    }

    public static int countDigits(int num) {
        int count = 0;
        while (num > 0) {
            num = num / 10;
            count++;
        }
        return count;
    }
}
